﻿using Kingdee.BOS;
using Kingdee.BOS.App.Data;
using Kingdee.BOS.Authentication;
using Kingdee.BOS.Contracts;
using Kingdee.BOS.Core.DynamicForm;
using Kingdee.BOS.Core.DynamicForm.PlugIn;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Core.Log;
using Kingdee.BOS.Log;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.ServiceFacade.KDServiceClient.User;
using Kingdee.BOS.ServiceFacade.KDServiceFx;
using Kingdee.BOS.ServiceHelper;
using Kingdee.BOS.Util;
using Kingdee.BOS.WebApi.Client;
using Kingdee.BOS.WebApi.ServicesStub;
using Kingdee.K3.FIN.App.Core.Match;
using Kingdee.K3.FIN.Contracts;
using Kingdee.K3.FIN.Core;
using Kingdee.K3.FIN.Core.Match.Object;
using Kingdee.K3.FIN.Core.Parameters;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LiMinCRMPlugin.VerificationApi
{
    /// <summary>
    /// 手工核销API
    /// </summary>
    [Description("手工核销API")]
    [HotUpdate]
    public class ManualWriteOffApi : AbstractWebApiBusinessService
    {
        //固定写法,GetCust和上面类名称一致
        public ManualWriteOffApi(KDServiceContext context)
            : base(context)
        {
        }
        //接收Json, 返回JObject
        public string ExecuteService(string parameter)
        {
            //        {
            //            "parameter": {
            //                "UserId": 100256,
            //    "GenBillDate": "2024-02-29",
            //    "data": [
            //        {
            //                    "FMatchType": "3",
            //            "FFormId": "AR_receivable",
            //            "FBILLID": "116162",
            //            "FENTRYID": "116555",
            //            "FTHEMATCHAMOUNT": 276.11,
            //            "FTHEMATCHQTY": 0
            //        },
            //        {
            //                    "FMatchType": "3",
            //            "FFormId": "AR_RECEIVEBILL",
            //            "FBILLID": "100961",
            //            "FENTRYID": "100961",
            //            "FTHEMATCHAMOUNT": 176.11,
            //            "FTHEMATCHQTY": 0
            //        },
            //        {
            //                    "FMatchType": "3",
            //            "FFormId": "AR_RECEIVEBILL",
            //            "FBILLID": "100962",
            //            "FENTRYID": "100962",
            //            "FTHEMATCHAMOUNT": 100,
            //            "FTHEMATCHQTY": 0
            //        }
            //    ]
            //}
            //        }
            //解析传入JSON
            Dictionary<string, object> dicJson = JsonConvert.DeserializeObject<Dictionary<string, object>>(parameter);
            //将data数据部分转换为JsonArray对象
            JArray datArray = JArray.Parse(dicJson["data"].ToString());
            string UserNo = Convert.ToString(dicJson["UserId"]);//用户ID           
            DateTime GenBillDate = Convert.ToDateTime(dicJson["GenBillDate"].ToString());//核销日期
            //核销数组
            List<SpecialMatchDateForUser> MatchDataList = new List<SpecialMatchDateForUser>();
            foreach (var dJ in datArray)
            {
                string FMatchType = dJ["FMatchType"].ToString();//核销类型
                string FFormId = dJ["FFormId"].ToString();//表单标识
                long FBILLID = Convert.ToInt64(dJ["FBILLID"].ToString());//单据头内码
                long FENTRYID = Convert.ToInt64(dJ["FENTRYID"].ToString());//单据体内码
                decimal FTHEMATCHAMOUNT = Convert.ToDecimal(dJ["FTHEMATCHAMOUNT"].ToString());//核销金额
                decimal FTHEMATCHQTY = Convert.ToDecimal(dJ["FTHEMATCHQTY"].ToString());//核销数量

                //将解析后的Data数据封装           
                SpecialMatchDateForUser MatchData = new SpecialMatchDateForUser();
                MatchData.FMatchType = FMatchType;
                MatchData.FFormId = FFormId;
                MatchData.FBillId = FBILLID;
                MatchData.FEntryID = FENTRYID; ;
                MatchData.FTheMatchAmount = FTHEMATCHAMOUNT;
                MatchData.FTheMatchQty = FTHEMATCHQTY;
                MatchDataList.Add(MatchData);
            }
            string Result;
            IOperationResult operationResult = WriteOff("3", 36, UserNo, GenBillDate, MatchDataList);
            if (operationResult.IsSuccess)
            {
                var OR = operationResult.OperateResult;
                foreach (var item in OR)
                {
                    string No = Convert.ToString(item.Message);
                    No = No.Substring(No.IndexOf("为")+1, No.IndexOf("！")-No.IndexOf("为")-1);
                    item.Number = No;
                }
               
                Result = JsonConvert.SerializeObject(OR);
            }
            else
            {
                Result = JsonConvert.SerializeObject(operationResult.ValidationErrors);
            }
            return Result;
        }




        /// <summary>
        /// 写日志
        /// </summary>
        /// <param name="Desc">错误描述</param>
        /// <param name="DName">操作名称</param>
        /// <param name="BillName">单据名称</param>
        /// <param name="subID">领域编号</param> 应付单=50
        /// <returns></returns>
        public bool GetLog(string Desc, string DName, string BillName, string subID)
        {
            bool Judge = false;
            try
            {
                //保存上机日志
                var logs = new List<LogObject>();
                var log = new LogObject();
                log.pkValue = BillName;
                log.Description = Desc;
                log.OperateName = DName;
                log.ObjectTypeId = "";
                log.SubSystemId = subID;
                log.Environment = OperatingEnvironment.BizOperate;
                logs.Add(log);
                LogServiceHelper.BatchWriteLog(this.KDContext.Session.AppContext, logs);
                //保存文档日志
                Logger.Info(BillName + "-" + DName, Desc);
                Logger.Error(BillName + "-" + DName, Desc, new KDException("?", "金蝶异常......"));
                var logFilePath = AppDomain.CurrentDomain.BaseDirectory + "App_Data\\Log\\" + DateTime.Now.ToString("yyyy-MM-dd") + "\\Cloud.log";
                Judge = true;
            }
            catch (Exception)
            {
            }
            return Judge;
        }




        /// <summary>
        /// 核销接口调用
        /// </summary>
        /// <param name="MatchType">核销类型（1应付付款，2应付开票，3应收收款，4应收开票，必填）</param>
        /// <param name="MatchMethodID">核销方式</param>
        /// <param name="UserId">用户ID</param>
        /// <param name="MatchDatas">产生核销单的日期</param>
        /// <param name="GenBillDate">核销数据</param>
        /// <returns></returns>
        public IOperationResult WriteOff(string MatchType, int MatchMethodID, string UserNo, DateTime GenBillDate, List<SpecialMatchDateForUser> MatchDatas)
        {
            string SQL = string.Format(@"/*dialect*/select FUSERID from T_SEC_USER where FUserAccount='{0}'", UserNo);
            DataTable dtUser = DBUtils.ExecuteDataSet(this.KDContext.Session.AppContext, SQL).Tables[0];
            int UserId = 0;
            if (dtUser.Rows.Count > 0)
            {
                UserId = Convert.ToInt32(dtUser.Rows[0]["FUSERID"]);
            }
            //构造核销参数
            MatchParameters para = new MatchParameters();
            para.MatchType = MatchType;
            para.MatchMethodID = MatchMethodID; //外部匹配核销，38是手工特殊核销，也就是先走匹配，匹配之后剩余的金额会进行特殊核销           
            para.UserId = UserId;
            para.SelectedSchemeId = new List<object> { 20008 };// 核销方案内码
            para.GenBillDate = GenBillDate;

            //调用接口
            var o = Kingdee.K3.FIN.Contracts.ServiceFactory.GetService<IMatchService>(this.KDContext.Session.AppContext);
            IOperationResult result = o.SpecialMatchForUser(this.KDContext.Session.AppContext, para, MatchDatas);

            //string[] rs;
            //if (result.IsSuccess)//成功
            //{
            //    rs = new string[result.OperateResult.Count];
            //    int i = 0;
            //    foreach (var row in result.OperateResult)
            //    {
            //        rs[i]=row.Message; 
            //        i++;
            //    }
            //}
            //else
            //{
            //    rs = new string[result.ValidationErrors.Count];
            //    int i = 0;
            //    foreach (var row in result.ValidationErrors)
            //    {
            //        rs[i] = row.Message;
            //        i++;
            //    }
            //}

                return result;
        }

    }
}

